// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System;
using System.Data;

namespace SnapObjects.Data
{
    internal class DataTableImporter : IDataTableImporter
    {
        private readonly DataTable _dataTable;

        public DataTableImporter(DataTable dataTable)
        {
            _dataTable = dataTable;
        }

        public int Import(string raw, DataFormat format, DataFormatSetting setting = null)
        {
            var formater = DataFormaterFactory.GetReadFormater(raw, format, setting);

            this.ImportSimpleRows(formater);

            return _dataTable.Rows.Count;
        }

        private void ImportSimpleRows(IDataReadFormater<object> formater)
        {
            foreach (var item in formater.GetModelEntries())
            {
                if (_dataTable.Columns.Count < 1)
                {
                    this.ImportMetaColumns(item);
                }

                var row = _dataTable.NewRow();

                foreach (var property in item.Properties)
                {
                    row[property] = item.GetCurrentValue(property) ?? DBNull.Value;
                }

                _dataTable.Rows.Add(row);
            }
        }

        private void ImportMetaColumns(IModelEntry<object> entry)
        {
            foreach (var property in entry.Properties)
            {
                var type = entry.GetCurrentValue(property)?.GetType() ?? typeof(object);

                var column = new DataColumn(property, type);

                _dataTable.Columns.Add(column);
            }
        }
    }
}
